package com.wfw.feichat.service.impl;

import com.wfw.feichat.entity.Friend;
import com.wfw.feichat.entity.User;
import com.wfw.feichat.mapper.FriendMapper;
import com.wfw.feichat.service.FriendService;
import com.wfw.feichat.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: wfw
 * @date: 2019-05-21 16:31
 */
@Service
@Slf4j
public class FriendServiceImpl implements FriendService {
    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private UserService userService;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Friend getFriendByUidAndFriendUid(String uid, String friendUid) {
        if (StringUtils.isBlank(uid) || StringUtils.isBlank(friendUid)) {
            return null;
        }
        Friend friend = new Friend();
        friend.setUid(uid);
        friend.setFriendUid(friendUid);
        friend = friendMapper.selectOne(friend);
        return friend;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer addFriend(String uid, String friendUid) {
        if (StringUtils.isBlank(uid) || StringUtils.isBlank(friendUid)) {
            return 0;
        }
        Friend friend = getFriendByUidAndFriendUid(uid, friendUid);
        if (friend != null) {
            return 0;
        }
        User user1 = userService.getUserById(uid);
        User user2 = userService.getUserById(friendUid);
        if (user1 == null || user2 == null) {
            return 0;
        }
        friend = new Friend();

        String friendId = Sid.nextShort();
        Friend friend1 = friendMapper.selectByPrimaryKey(friendId);
        while (friend1 != null) {
            friendId = Sid.nextShort();
            friend1 = friendMapper.selectByPrimaryKey(friendId);
        }
        friend.setId(friendId);

        friend.setUid(uid);
        friend.setFriendUid(friendUid);
        Integer result = friendMapper.insert(friend);
        return result;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<String> getfriendUidListByUid(String uid) {
        if (StringUtils.isBlank(uid)) {
            return null;
        }
        return friendMapper.getfriendUidListByUid(uid);
    }

}
